/**
 * 
 */
package controller.xml;

import model.session.SessionBlock;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

/**
 * Use to parse a {@link SessionBlock} in the exported session in XML.
 * 
 * @author GRONOWSKI Stephane svan001@aol.com
 * 
 *         igsat 2010
 * 
 */
public class SessionBlockXMLHandler extends XMLHandler {

	private Long					previousTime	= null;
	private SessionBlockXMLStatus	status			= SessionBlockXMLStatus.NONE;


	@Override
	public boolean characters2(char[] ch, int start, int length) throws SAXException {

		switch (status) {
		case NONE:
			throw new SAXException("not supposed to receive character in this status");
		default:
			return super.characters2(ch, start, length);
		}
	}

	@Override
	public boolean endDocument2() throws SAXException {
		return false;
	}

	@Override
	public boolean endElement2(String uri, String localName, String qName) throws SAXException {
		if (status == SessionBlockXMLStatus.NONE)
			return false;

		if (status == SessionBlockXMLStatus.PREVIOUS_EXEC_TIME && qName.equals(XMLBaliseFormat.PREVIOUS_TIME))
		{// balise previous time
			setPreviousTime();
			status = SessionBlockXMLStatus.NONE;
			return true;
		}

		// attend une fin de balise qui existe pas...
		throw new SAXException("an other end of element was expected");
	}

	@Override
	public boolean startElement2(String arg0, String arg1, String arg2, Attributes arg3) throws SAXException {
		if (status != SessionBlockXMLStatus.NONE)
			throw new SAXException("already have a started element");

		if (arg2.equals(XMLBaliseFormat.PREVIOUS_TIME))
		{// balise previous time
			if (previousTime != null)
				throw new SAXException("already had a PREVIOUS TIME");
			status = SessionBlockXMLStatus.PREVIOUS_EXEC_TIME;
			return true;
		}

		// peut pas commencer balise qui existe pas
		throw new SAXException("unexpected balise: " + arg2);
	}


	/**
	 * Set the previous execution time.
	 * 
	 * @throws SAXException
	 */
	private void setPreviousTime() throws SAXException {
		try
		{
			previousTime = Long.valueOf(buffer.toString());
		} catch (Exception e)
		{
			throw new SAXException("bad long value for PREVIOUS TIME");
		}

	}

	/**
	 * Return the previousTime.
	 * 
	 * @return the previousTime
	 */
	public Long getPreviousTime() {
		return previousTime;
	}

}
